package com.escom.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.escom.entidad.HospitalVO;
import com.escom.utils.Constantes;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Carlos on 7/04/14.
 */
public class HospitalDAO {

    private Context context;

    public HospitalDAO(Context context){
        this.context = context;
    }

    public void createMultipleHospital(HospitalVO[] arrayHospital){
        DataBaseManager dataBaseManager = new DataBaseManager(this.context);
        SQLiteDatabase sqLiteDatabase = dataBaseManager.getWritableDatabase();
        if (sqLiteDatabase != null){
            for (int i = 0 ; i < arrayHospital.length; i++){
                HospitalVO hospital = arrayHospital[i];
                ContentValues contentValues = new ContentValues();
                contentValues.put(DataBaseManager.ID_HOSPITAL, hospital.getIdHospital());
                contentValues.put(DataBaseManager.HOSPITAL, hospital.getHospital());
                try {
                    sqLiteDatabase.insertOrThrow(DataBaseManager.HLC_HOSPITAL_CAT, null, contentValues);
                } catch (android.database.sqlite.SQLiteConstraintException exSQL) {
                    Log.d(Constantes.LOG_ID, this.getClass().getName() +  " Update(Error administrado)");
                    sqLiteDatabase.update(DataBaseManager.HLC_HOSPITAL_CAT, contentValues,
                            DataBaseManager.ID_HOSPITAL + " = " + hospital.getIdHospital(), null);
                }
            }
            sqLiteDatabase.close();
        }
    }

    public List<HospitalVO> retrieveHospital(){
        Log.d("Logger HospitalDAO", "retrieveHospital");
        DataBaseManager dataBaseManager = new DataBaseManager(this.context);
        SQLiteDatabase sqLiteDatabase = dataBaseManager.getWritableDatabase();
        Cursor cursor = sqLiteDatabase.rawQuery("SELECT "
                + "ho.id_hospital,"
                + "ho.hospital"
                + "FROM"
                + "hospital",null);

        List<HospitalVO> hospitales = new ArrayList<HospitalVO>();
        if (cursor.moveToFirst()) {
            do {
                HospitalVO hospital = new HospitalVO();
                hospital.setIdHospital(String.valueOf(cursor.getInt(0)));
                hospital.setHospital(cursor.getString(1));
            }while (cursor.moveToNext());

        }else{
            Log.d("Logger HospitalDAO", "NULO");
        }
        sqLiteDatabase.close();
        return hospitales;
    }

}
